package com.ronan.common.utils;

import com.google.protobuf.MessageLite;
import com.ronan.common.constant.Constants;
import com.ronan.common.proto.Business;
import com.ronan.common.proto.Heart;
import com.ronan.common.proto.Login;
import com.ronan.common.proto.Message;
import lombok.extern.slf4j.Slf4j;

/**
 * FileName    : com.ronan.imserver.utils
 * Description : 维护 指令<->消息proto 的关系
 *
 * @author : ysk
 * @version : 1.0
 * Create Date : 2021/2/26 0:23
 **/
@Slf4j
public enum RIMCommandManager {

    LOGIN(Constants.MsgConstant.LOGIN, Login.getDefaultInstance()),
    HEART(Constants.MsgConstant.HEART, Heart.getDefaultInstance()),
    MESSAGE(Constants.MsgConstant.MESSAGE, Message.getDefaultInstance()),
    BUSINESS(Constants.MsgConstant.BUSINESS, Business.getDefaultInstance());

    private final int command;
    private final MessageLite body;

    RIMCommandManager(int command, MessageLite body) {
        this.command = command;
        this.body = body;
    }

    /**
     * 根据指令查找消息类型
     *
     * @param command 命令
     * @return {@link MessageLite}
     */
    public static MessageLite getBodyByCommand(int command) {
        for (RIMCommandManager value : RIMCommandManager.values()) {
            if (value.command == command) {
                return value.body;
            }
        }
        log.error("error command : {}", command);
        throw new RuntimeException("error command : " + command);
    }

    /**
     * 根据消息类型得到指令
     *
     * @param body 消息类型
     * @return int
     */
    public static int getCommandByBody(MessageLite body) {
        for (RIMCommandManager value : RIMCommandManager.values()) {
            if (value.body.getClass() == body.getClass()) {
                return value.command;
            }
        }
        log.error("error body : {}", body.getClass().getName());
        throw new RuntimeException("error body : " + body.getClass().getName());
    }
}
